<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <h2>点击切换颜色</h2>
        <div class="item" style="margin: 10px;width: 50px;height: 50px;background-color: red"></div>
        <div class="item" style="margin: 10px;width: 50px;height: 50px;background-color: red"></div>
        <div class="item" style="margin: 10px;width: 50px;height: 50px;background-color: red"></div>
    </div>

    <script>
        //获取div的元素对象
        let items = document.getElementsByClassName('item');
        // 遍历并绑定事件
        for (var i = 0; i < items.length; i++) {
            items[i].onclick = function () {
                //修改当前元素的背景颜色
                // this.style.background = 'pink';正常
                items[i].style.background = 'pink' //error
            }
        }
        console.log(i);//3
        // 报错原因：循环结束后i=3 点击事件触发时，数组下标越界；
        // 解决：将var换成let  let具有块级作用域，互不影响
    </script>
</body>

</html>